<template>
  <el-dialog
    title="选择角色"
    v-model="isShow"
    width="30%"
    :close-on-click-modal="false"
    align-center
  >
    <el-form
      label-width="80px"
      class="role-form"
    >
      <el-form-item label="角色列表">
        <el-select
          v-model="selectedRoleId"
          placeholder="请选择角色"
        >
          <el-option
            v-for="role in roleList"
            :key="role.id"
            :label="role.name"
            :value="role.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="当前角色">
        <el-input
          v-model="selectedRoleName"
          disabled
        />
      </el-form-item>
    </el-form>

    <span
      slot="footer"
      class="dialog-footer"
    >
      <el-button
        @click="handleCancel"
        size="large"
      >
        取消
      </el-button>

      <el-button
        type="primary"
        @click="handleConfirm"
        size="large"
      >
        确认
      </el-button>
    </span>
  </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref, watch, watchEffect } from 'vue'
import { getRoleList, getUserRole, setUserRole } from '@/api/role'
import { ElMessage } from 'element-plus'

const isShow = defineModel()
const roleList = ref([])
const selectedRoleId = ref(null)
const selectedRoleName = ref('')

const props = defineProps({
  userId: {
    type: Number,
    default: 0
  }
})

onMounted(async () => {
  await fetchRoleList()
})

watch(selectedRoleId, () => {
  selectedRoleName.value = roleList.value.find(
    (role: any) => role.id === selectedRoleId.value
  )?.name
})

const fetchRoleList = async () => {
  roleList.value = await getRoleList()
  if (props.userId) {
    const roleId = await getUserRole({ userId: props.userId })
    selectedRoleId.value = roleId !== 0 ? roleId : ''
  }
}

const handleCancel = () => {
  isShow.value = false
}

const handleConfirm = async () => {
  if (selectedRoleId.value) {
    await setUserRole({
      userId: props.userId,
      roleId: selectedRoleId.value
    })
    ElMessage.success('角色分配成功')
    isShow.value = false
  }
}

watchEffect(() => {
  if (isShow.value) {
    fetchRoleList()
  }
})
</script>

<style scoped lang="scss">
.role-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;

  .el-button {
    margin-left: 10px;
  }
}
</style>
